package vip.xiaonuo.megvii.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.springframework.stereotype.Service;
import vip.xiaonuo.core.pojo.response.ErrorResponseData;
import vip.xiaonuo.core.pojo.response.ResponseData;
import vip.xiaonuo.core.pojo.response.SuccessResponseData;
import vip.xiaonuo.digest.DigestHttpClient;
import vip.xiaonuo.digest.DigestHttpUtil;
import vip.xiaonuo.facedoor.modular.device.listener.DeviceChangeTypeEnum;
import vip.xiaonuo.facedoor.modular.device.listener.DevicePublisher;
import vip.xiaonuo.facedoor.modular.device.listener.DeviceSourceEnum;
import vip.xiaonuo.megvii.BaseConfig;
import vip.xiaonuo.megvii.config.model.ApiResponse;
import vip.xiaonuo.modular.devicemegvii.entity.DeviceMegvii;
import vip.xiaonuo.modular.devicemegvii.service.DeviceMegviiService;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.InetAddress;

@Service
@Slf4j
public class DeviceMegviiConfigService {

    @Resource
    private DeviceMegviiService deviceMegviiService;

    @Resource
    private DevicePublisher publisher;

    /**
     * 检查配置参数的正确性以及设备运行的状态
     * @param device
     * @param isPublish 是否发布消息
     * @return
     */
    public ResponseData check(DeviceMegvii device,boolean isPublish) {
        if(device==null){
            return new ErrorResponseData(-1,"业务数据不存在");
        }

        String url = DeviceMegviiBaseService.getMachAddress(device);
        if(url==null || url.length()==0){
            return new ErrorResponseData(-1,"参数不完整,请检查");
        }

        try {
            boolean isReachable = InetAddress.getByName(device.getMachServerAddress()).isReachable(5000);
            if(!isReachable){
                device.setMachStatus(0);
                return new ErrorResponseData(-1,"访问设备失败,请检查网络连接或修改设备地址");
            }
            HttpClient client = DigestHttpClient.getDigestHttpClient(device);
            String getConfigUrl = url + BaseConfig.URL_CONFIG;
            ApiResponse resp = DigestHttpUtil.sendGet(client,getConfigUrl);

            Integer code = resp.getCode();
            if(code == 200 || code == 0 ){
                device.setMachStatus(3);
                new Thread(new UpdateConfigParam(device)).start();
                return new SuccessResponseData(ResponseData.DEFAULT_SUCCESS_CODE,"连接成功",null);
            }else if(code == 401){
                device.setMachStatus(2);
            }else{
                device.setMachStatus(1);
            }
            return new ErrorResponseData(code,resp.getMessage());
        } catch (IOException e) {
            device.setMachStatus(0);
            return new ErrorResponseData(-1,"访问设备异常,请检查网络连接或修改设备地址");
        }finally {
            // 事件发布
            if(isPublish){
                deviceMegviiService.saveOrUpdate(device);
                publisher.publishEvent(DeviceChangeTypeEnum.EDIT, DeviceSourceEnum.AI_BOX,device);
            }

        }
    }


    class UpdateConfigParam implements Runnable{

        private DeviceMegvii device;

        UpdateConfigParam(DeviceMegvii device){
            this.device = device;
        }

        @Override
        public void run() {
            String url = DeviceMegviiBaseService.getMachAddress(device);
            if(url==null || url.length()==0){
                return;
            }
            HttpClient client = DigestHttpClient.getDigestHttpClient(device);
            String getConfigUrl = url + BaseConfig.URL_DEVICE;
            ApiResponse resp = DigestHttpUtil.sendGet(client,getConfigUrl);

            Integer code = resp.getCode();
            if(code == 200 || code == 0 ){
                Object obj = resp.getData();
                String json = JSON.toJSONString(obj);
                JSONObject jsonBean = JSON.parseObject(json,JSONObject.class);

                String machNo = jsonBean.containsKey("deviceId") ? jsonBean.getString("deviceId") : device.getMachNo();
                String snNo = jsonBean.containsKey("serialNumber") ? jsonBean.getString("serialNumber") : device.getSnCode();
                device.setMachNo(machNo);
                device.setSnCode(snNo);
                deviceMegviiService.saveOrUpdate(device);
                // 事件发布
                publisher.publishEvent(DeviceChangeTypeEnum.EDIT, DeviceSourceEnum.AI_BOX,device);
            }
        }
    }

}
